/*
 * Copyright (C) 2011 Mette Bank, Rikke Jensen, Kenneth Brodersen, Thomas Pedersen
 * 
 * This file is part of digiPECS.
 * 
 * digiPECS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * digiPECS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with digiPECS.  If not, see <http://www.gnu.org/licenses/>.
 */

package sw6.digipecs.widget;

import sw6.digipecs.R;
import sw6.digipecs.exceptions.ImageIsEmptyException;
import sw6.digipecs.exceptions.SoundNotFoundException;
import sw6.digipecs.helpers.AudioPlayer;
import sw6.digipecs.model.ExtImage;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

public class ExtImageView extends FrameLayout {
	private ImageView mImgView;
	private TextView mTextView;
	private ExtImage mExtImage;
	
	public ExtImageView(Context context) {
		super(context);
		init(context);
	}
	
	public ExtImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}
	
	private void init(Context context) {
		String infService = Context.LAYOUT_INFLATER_SERVICE; 
		LayoutInflater li; 
		li = (LayoutInflater)getContext().getSystemService(infService); 
		li.inflate(R.layout.extimageview, this,true);
		
		mImgView = (ImageView)findViewById(R.id.image);		
		mTextView = (TextView)findViewById(R.id.text);
	}

	public void setImage(ExtImage image) {
		mExtImage = image;
		
		try {
			image.setImage(mImgView);
			String text = image.getText();
			if(text.equals("")){;
				mTextView.setPadding(0, 0, 0, 0);
			}
			mTextView.setText(text);
		} catch (ImageIsEmptyException e) {
			mTextView.setPadding(0, 0, 0, 0);
		}
	}
	
	public ExtImage getImage() {
		return mExtImage;
	}
	
	public void play() {
		// Running this in the background to keep UI reponsive and smooth
		new Thread(new Runnable() {
			@Override
			public void run() {
				if (mExtImage.hasSound()) {
					try {
						AudioPlayer.play(mExtImage.getSound(), null);
					} catch (ImageIsEmptyException e) {
					} catch (SoundNotFoundException e) {
					}
				}
			}
		}).start();
	}

}
